package org.dromara.tearoom.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class RestLogUtil implements ClientHttpRequestInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(RestLogUtil.class);
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        // 记录请求日志
        logRequest(request, body);

        // 执行请求并获取响应
        ClientHttpResponse response = execution.execute(request, body);

        // 复制响应流以支持多次读取
        byte[] responseBody = StreamUtils.copyToByteArray(response.getBody());
        response = new BufferedClientHttpResponse(response, responseBody);

        // 记录响应日志
        logResponse(response);

        return response;
    }

    private void logRequest(HttpRequest request, byte[] body) {
        // 示例：打印请求URI和请求体
        LOGGER.info("Request URI: " + request.getURI());
        LOGGER.info("Request Body: " + new String(body, StandardCharsets.UTF_8));
    }

    private void logResponse(ClientHttpResponse response) throws IOException {
        LOGGER.info("Response Status: " + response.getStatusCode());
        LOGGER.info("Response Body: " + new String(response.getBody().readAllBytes(), StandardCharsets.UTF_8));
    }

    // 包装响应类以支持多次读取Body
    private static class BufferedClientHttpResponse implements ClientHttpResponse {
        private final ClientHttpResponse originalResponse;
        private final byte[] body;

        public BufferedClientHttpResponse(ClientHttpResponse originalResponse, byte[] body) {
            this.originalResponse = originalResponse;
            this.body = body;
        }

        @Override
        public InputStream getBody() {
            return new ByteArrayInputStream(body);
        }

        @Override
        public HttpHeaders getHeaders() {
            return originalResponse.getHeaders();
        }

        @Override
        public HttpStatusCode getStatusCode() throws IOException {
            return originalResponse.getStatusCode();
        }

        @Override
        @Deprecated
        public String getStatusText() throws IOException {
            return originalResponse.getStatusText();
        }

        @Override
        public void close() {
            originalResponse.close();
        }
    }
}
